package com.service;

import com.domain.User;
import com.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiUserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    public User findById(int user_id) {
        //先从Redis缓存中查询数据
        Object object = redisTemplate.opsForValue().get("user_" + user_id);
        if (object != null) {
            return (User) object;
        } else {
            //缓存中没有，就进入数据库查询
            Optional<User> optional = userRepository.findById(user_id);
            if (optional.isPresent()) {
                User user = optional.get();
                //将查询的结果进行缓存，并设置有效期为1天
                redisTemplate.opsForValue().set("user_" + user_id, user, 1, TimeUnit.DAYS);
                return user;
            } else {
                return null;
            }
        }
    }

    public User updateUser(User user) {
        userRepository.updateUser(user.getId(), user.getPwd());
        //更新数据后进行缓存更新
        redisTemplate.opsForValue().set("user_" + user.getId(), user);
        return user;
    }

    public void deleteUser(int user_id) {
        userRepository.deleteById(user_id);
        redisTemplate.delete("user_" + user_id);
    }

}
